/* polyfill */
require('./vue-detective.polyfill')
/* util */
const madge = require('madge')
const colors = require('colors')
const { writeFileSync, getProjectPath } = require('../../cli/common')
const { stringify } = require('./string')

// 存放依赖树的路径
const treePath = getProjectPath('/script/model/madgeTree.js')

// 用 madge 库计算依赖树的示例代码，具体可查看官方文档
function generateProjectTree() {
  const madgeAllPromises = ['./'].map(filePath => madge(`${filePath}`, getMadgeOptions()))
  
  console.log(`${colors.green('生成依赖数据中，请耐心等候，约一分钟左右...')}`)
  
  return (
    Promise.all(madgeAllPromises).then((result) => {
      result.forEach((event) => {
        const tree = event.obj()
        writeFileSync(treePath, `module.exports = ${stringify(filterTree(tree))}`)
        
        console.log(`${colors.green('更新依赖数据成功！')}`)
        
      })
    }).catch(error => {
      console.error(error)
      console.log(`${colors.red('更新依赖数据失败！')}`)
    })
  )
}

function filterTree(tree) {
  let newTree = {}
  let reg = /^(model|script|server|cli|config|modules)/
  
  Object.keys(tree).forEach(key => {
    if (reg.test(key)) return
    
    newTree[key] = tree[key]
  })
  
  return newTree
}

function getMadgeOptions() {
  return {
    fileExtensions: ['js', 'vue', 'ts', 'jsx', 'tsx'],
    webpackConfig: getProjectPath('/config/webpack.prod.conf.js'),
    tsConfig: getProjectPath('/tsconfig.json'),
    excludeRegExp: [/'^(model|script|server|cli)'/]
  }
}

function checkUpdate() {
  const isUpdate = process.argv[2] == 'update'
  if (isUpdate) {
    generateProjectTree()
  }
}

checkUpdate()

module.exports = generateProjectTree
